package com.juc.concurrency.jucExample.atomic;

import com.juc.concurrency.annoations.ThreadSafe;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * Java原子属性更新器AtomicReferenceFieldUpdater
 */
@Slf4j
@ThreadSafe
public class AtomicIntegerFieldUpdaterExample5 {

    private static AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterExample5> updater =
            AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterExample5.class, "count");


    /**
     * 注意 这里必须要有volatile修饰，且非static修饰
     */
    @Getter
    public volatile int count = 100;

    public static void main(String[] args) {

        AtomicIntegerFieldUpdaterExample5 example5 = new AtomicIntegerFieldUpdaterExample5();

        if (updater.compareAndSet(example5, 100, 120)) {
            log.info("update success 1, {}", example5.getCount());
        }

        if (updater.compareAndSet(example5, 100, 120)) {
            log.info("update success 2, {}", example5.getCount());
        } else {
            log.info("update failed, {}", example5.getCount());
        }
    }
}
